﻿using MQTTnet;
using MQTTnet.Client;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace FreeOPC.Client.Host
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            //Task.Factory.StartNew(() => {
            //    Subscribe_Topic();
            //}, TaskCreationOptions.LongRunning);
            Subscribe_Topic();
            Console.ReadLine();
        }

        public static async Task Subscribe_Topic()
        {
            /*
             * This sample subscribes to a topic.
             */
            var mqttFactory = new MqttFactory();
            var mqttClient = mqttFactory.CreateMqttClient();
            try
            {
                var mqttClientOptions = new MqttClientOptionsBuilder()
                    .WithTcpServer("127.0.0.1", 1883)
                    .WithCredentials("longdream", "Test")
                    .Build();
                // Setup message handling before connecting so that queued messages
                // are also handled properly. When there is no event handler attached all
                // received messages get lost.
                mqttClient.ApplicationMessageReceivedAsync += e =>
                {
                    string msg = System.Text.Encoding.Default.GetString(e.ApplicationMessage.Payload);
                    Console.WriteLine("Received application message." + msg);
                    return Task.CompletedTask;
                };
                var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
                  .WithTopicFilter(
                      f =>
                      {
                          f.WithTopic("mqttBusTopic");
                      })
                  .Build();
                await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
                await mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);
                Console.WriteLine("MQTT client subscribed to topic.");
                Console.WriteLine("Press enter to exit.");
            }
            catch (Exception ce)
            {

            }
        }
    }
}
